const { asyncHandler } = require('../../middleware/errorHandler');
const { success, error, paginate, paginateResponse } = require('../../utils/common');
const { Op } = require('sequelize');
const Course = require('../../models/Course');
const User = require('../../models/User');
const logger = require('../../utils/logger');

class CourseController {
  /**
   * 获取课程状态
   */
  static getStatus(k = '') {
    const status = {
      '-2': '管理员下架',
      '-1': '暂时下架',
      '0': '审核中',
      '1': '上架中',
      '2': '定时上架'
    };
    
    if (k === '') {
      return status;
    }
    return status[k] || '';
  }

  /**
   * 获取课程类别
   */
  static getSort(k = '') {
    const sort = {
      '0': '内容',
      '1': '课程',
      '2': '直播'
    };
    
    if (k === '') {
      return sort;
    }
    return sort[k] || '';
  }

  /**
   * 获取内容形式
   */
  static getTypes(k = '') {
    const type = {
      '1': '图文',
      '2': '视频',
      '3': '音频'
    };
    
    if (k === '') {
      return type;
    }
    return type[k] || '';
  }

  /**
   * 获取直播形式
   */
  static getLiveTypes(k = '') {
    const type = {
      '1': 'PPT',
      '2': '视频',
      '3': '音频'
    };
    
    if (k === '') {
      return type;
    }
    return type[k] || '';
  }

  /**
   * 获取支付方式
   */
  static getPayTypes(k = '') {
    const paytype = {
      '0': '免费',
      '1': '收费',
      '2': '密码'
    };
    
    if (k === '') {
      return paytype;
    }
    return paytype[k] || '';
  }

  /**
   * 获取试学类型
   */
  static getTrialTypes(k = '') {
    const trialtype = {
      '0': '否',
      '2': '进度'
    };
    
    if (k === '') {
      return trialtype;
    }
    return trialtype[k] || '';
  }

  /**
   * 获取课程模式
   */
  static getModes(k = '') {
    const mode = {
      '0': '自由',
      '1': '解锁'
    };
    
    if (k === '') {
      return mode;
    }
    return mode[k] || '';
  }

  /**
   * 课程列表
   */
  static index = asyncHandler(async (req, res) => {
    const { page = 1, limit = 10, status, title, teacher_id, category_id } = req.query;
    
    const where = {};
    if (status !== undefined) where.status = status;
    if (title) where.title = { [Op.like]: `%${title}%` };
    if (teacher_id) where.teacher_id = teacher_id;
    if (category_id) where.category_id = category_id;

    const { offset, limit: pageLimit } = paginate(page, limit);
    
    const { count, rows } = await Course.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ],
      offset,
      limit: pageLimit,
      order: [['created_at', 'DESC']]
    });

    res.json(paginateResponse(rows, count, page, limit));
  });

  /**
   * 添加课程页面数据
   */
  static add = asyncHandler(async (req, res) => {
    // 获取教师列表
    const teachers = await User.findAll({
      where: { role: 'teacher', status: 'active' },
      attributes: ['id', 'username', 'nickname'],
      order: [['created_at', 'DESC']]
    });

    // 获取分类数据
    const categories = await sequelize.query(
      'SELECT * FROM course_class ORDER BY list_order ASC',
      { type: sequelize.QueryTypes.SELECT }
    );

    // 获取年级数据
    const grades = await sequelize.query(
      'SELECT * FROM course_grade ORDER BY pid ASC, list_order ASC',
      { type: sequelize.QueryTypes.SELECT }
    );

    res.json(success({
      teachers,
      categories,
      grades,
      status: CourseController.getStatus(),
      sort: CourseController.getSort(),
      types: CourseController.getTypes(),
      liveTypes: CourseController.getLiveTypes(),
      payTypes: CourseController.getPayTypes(),
      trialTypes: CourseController.getTrialTypes(),
      modes: CourseController.getModes()
    }, '获取成功'));
  });

  /**
   * 添加课程
   */
  static addPost = asyncHandler(async (req, res) => {
    const {
      title,
      description,
      cover,
      teacher_id,
      category_id,
      price,
      original_price,
      duration,
      lessons_count,
      status,
      is_free,
      is_recommend,
      is_hot,
      tags,
      requirements,
      objectives,
      content_type,
      live_type,
      pay_type,
      trial_type,
      mode
    } = req.body;

    // 验证必填字段
    if (!title || !teacher_id) {
      return res.status(400).json(error('标题和教师为必填项'));
    }

    // 创建课程
    const course = await Course.create({
      title,
      description,
      cover,
      teacher_id,
      category_id,
      price: price || 0,
      original_price: original_price || 0,
      duration: duration || 0,
      lessons_count: lessons_count || 0,
      status: status || 'draft',
      is_free: is_free || false,
      is_recommend: is_recommend || false,
      is_hot: is_hot || false,
      tags: tags ? JSON.parse(tags) : [],
      requirements,
      objectives,
      content_type,
      live_type,
      pay_type,
      trial_type,
      mode
    });

    logger.info(`管理员 ${req.user.id} 创建课程: ${course.id}`);

    res.json(success(course, '课程创建成功'));
  });

  /**
   * 编辑课程页面数据
   */
  static edit = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const course = await Course.findByPk(id, {
      include: [
        {
          model: User,
          as: 'teacher',
          attributes: ['id', 'username', 'nickname', 'avatar']
        }
      ]
    });

    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 获取教师列表
    const teachers = await User.findAll({
      where: { role: 'teacher', status: 'active' },
      attributes: ['id', 'username', 'nickname'],
      order: [['created_at', 'DESC']]
    });

    // 获取分类数据
    const categories = await sequelize.query(
      'SELECT * FROM course_class ORDER BY list_order ASC',
      { type: sequelize.QueryTypes.SELECT }
    );

    // 获取年级数据
    const grades = await sequelize.query(
      'SELECT * FROM course_grade ORDER BY pid ASC, list_order ASC',
      { type: sequelize.QueryTypes.SELECT }
    );

    res.json(success({
      course,
      teachers,
      categories,
      grades,
      status: CourseController.getStatus(),
      sort: CourseController.getSort(),
      types: CourseController.getTypes(),
      liveTypes: CourseController.getLiveTypes(),
      payTypes: CourseController.getPayTypes(),
      trialTypes: CourseController.getTrialTypes(),
      modes: CourseController.getModes()
    }, '获取成功'));
  });

  /**
   * 更新课程
   */
  static editPost = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const updateData = req.body;

    const course = await Course.findByPk(id);
    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 更新课程
    await course.update(updateData);

    logger.info(`管理员 ${req.user.id} 更新课程: ${id}`);

    res.json(success(null, '课程更新成功'));
  });

  /**
   * 删除课程
   */
  static del = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const course = await Course.findByPk(id);
    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    // 软删除
    await course.update({ status: 'archived' });

    logger.info(`管理员 ${req.user.id} 删除课程: ${id}`);

    res.json(success(null, '课程删除成功'));
  });

  /**
   * 设置课程状态
   */
  static setStatus = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { status } = req.body;

    const course = await Course.findByPk(id);
    if (!course) {
      return res.status(404).json(error('课程不存在'));
    }

    await course.update({ status });

    logger.info(`管理员 ${req.user.id} 设置课程状态: ${id} -> ${status}`);

    res.json(success(null, '状态设置成功'));
  });

  /**
   * 批量操作
   */
  static batch = asyncHandler(async (req, res) => {
    const { ids, action } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json(error('请选择要操作的课程'));
    }

    switch (action) {
      case 'publish':
        await Course.update({ status: 'published' }, { where: { id: ids } });
        break;
      case 'unpublish':
        await Course.update({ status: 'draft' }, { where: { id: ids } });
        break;
      case 'delete':
        await Course.update({ status: 'archived' }, { where: { id: ids } });
        break;
      default:
        return res.status(400).json(error('无效的操作'));
    }

    logger.info(`管理员 ${req.user.id} 批量操作课程: ${action} - ${ids.join(',')}`);

    res.json(success(null, '批量操作成功'));
  });

  /**
   * 获取课程统计
   */
  static stats = asyncHandler(async (req, res) => {
    const total = await Course.count();
    const published = await Course.count({ where: { status: 'published' } });
    const draft = await Course.count({ where: { status: 'draft' } });
    const archived = await Course.count({ where: { status: 'archived' } });

    res.json(success({
      total,
      published,
      draft,
      archived
    }, '获取成功'));
  });
}

module.exports = CourseController; 